package com.abing.permissionsys.security.service;

import com.abing.permissionsys.entity.vo.SysUserVO;
import com.abing.permissionsys.service.MenuService;
import com.abing.permissionsys.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@Service
@CacheConfig(cacheNames = "role")
@Slf4j
public class JwtPermissionService {

    @Autowired
    private MenuService menuService;

    /**
     * key的名称如有修改，请同步修改 UserServiceImpl 中的 update 方法
     * @param user
     * @return
     */
    @Cacheable(key = "'loadPermissionByUser:' + #p0.username")
    public Collection<GrantedAuthority> mapToGrantedAuthorities(SysUserVO user) {

        System.out.println("--------------------loadPermissionByUser:" + user.getUsername() + "---------------------");
        List<String> roles = menuService.listPerms(user.getUserId());

        List<GrantedAuthority> grantedAuthorities=new ArrayList<>();
        for (String roleId:roles){
           if (StringUtils.isEmpty(roleId)){
               roleId=user.getUsername();
           }
            grantedAuthorities.add(new SimpleGrantedAuthority(roleId));
        }
        return grantedAuthorities;
    }
}
